<template>
  <div>
    <div v-if="editOpen">
      <t-table  :selected-row-keys="selectedRowKeys"
                @select-change="(val)=>{selectedRowKeys=val}" :data="data"
                :columns="columns" rowKey="id">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #content="{row}">
          <t-textarea clearable @change="()=>{ if(row.content!==''){row.contentStatus='default'} }" :status="row.contentStatus" :autosize="{minRows: 3}" v-model="row.content">
            <div slot="tips" v-if="row.contentStatus==='error'">不能为空</div>
          </t-textarea>
          <!-- <tiny-mce-editor v-model="row.content"></tiny-mce-editor> -->
        </template>
      </t-table>
      <div style="margin-top: 10px" class="btn-group-inline">
        <t-button @click="addData">新增</t-button>
        <t-button @click="upData">上移</t-button>
        <t-button @click="downData">下移</t-button>
        <t-button @click="delData">删除</t-button>
      </div>
    </div>
    <div v-else>
      <t-table  :selected-row-keys="selectedRowKeys"
                @select-change="(val)=>{selectedRowKeys=val}" :data="data"
                :columns="columns2" rowKey="id">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #content="{row}">
          {{ row.content }}
        </template>
      </t-table>
    </div>

  </div>
</template>

<script>
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";

export default {
  name: "contract-terms",
  components: {
    TinyMceEditor,
  },
  props:{
    value:{
      type: Array,
      default: () => [],
    },
    projectId: [String,Number],
    // contractId: [String,Number],
    editOpen: {
      type: Boolean,
      default: false
    },
  },
  data(){
    return {
      selectedRowKeys: [],
      data:[],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "content",
          title: "条款内容",
          align: "center",
        },
      ],
      columns2: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "content",
          title: "条款内容",
          align: "center",
        },
      ],
    }
  },
  watch: {
    // projectId: {
    //   immediate: true,
    //   handler(val) {
    //     if (val) {
    //       this.getData(val);
    //     }
    //   }
    // },
    value:{
      deep: true,
      immediate: true,
      handler(val) {
        if(val && val.length>0){
          const newArr = val.map(data=> ({
            ...data,
            initType: 'init'
          }))
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
          // this.$emit("input", val);
        }

      }
    },
    data:{
      deep: true,
      immediate: true,
      handler(val) {
        const newData = val.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    }
  },
  methods:{
    checkData(){
      // 合作单位 非空判断
      const isValidate = this.data.every((val, index) => {
        if (!val.content) {
          this.$set(this.data[index], 'contentStatus', 'error')
          this.$message.error(`其它条款：第${index + 1}条"条款"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'contentStatus', 'default')
        return true;
      });
      return isValidate;
    },
    // getData(){
    //   if(this.projectId){
    //     this.$api.kjxm.contract.termsGetByContractId(Number(this.contractId)).then(response => {
    //       this.data = response.data;
    //       this.$emit("input", this.data);
    //     }).catch((e) => {
    //       this.$message.error(e.toString());
    //     });
    //   }
    // },
    addData() {
      this.data.push({
        id: Date.parse(new Date()),
        content: "",
        projectId: Number(this.projectId),
        // contractId: this.contractId
      })
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style scoped>

</style>
